﻿using Elmah;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace Todo.Api.CustomAttributes
{
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {

            if (context.Exception != null)
            {
                // Log the error using Elmah
                ErrorSignal.FromCurrentContext().Raise(context.Exception);
                
                // Create generic error
                var errorResponse = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                    "An error occured while processing your request. Error has been logged and the site admin has been notified...",
                    context.Exception);
                
                // Set the response with generic error - this add the call stack to the response
                context.Response = errorResponse;
               
                // Let the process flow...
                base.OnException(context);
            }
        }
    }
}